package cn.com.cis.utils.jobExecute;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import cn.com.cis.service.ETLExecutorService;
import cn.com.cis.service.GenerateXmlService;
import cn.com.cis.service.JobLogService;
import cn.com.cis.service.XmlJobService;
import cn.com.cis.utils.SpringContextUtil;
import scriptella.execution.EtlExecutorException;

public class JobExecuteHelper {

	private static GenerateXmlService	generateXmlService;
	private static ETLExecutorService	etlExecutorService;
	private static XmlJobService		xmlJobService;
	private static JobLogService		js;

	private static void initServices() {
		if (null == generateXmlService || null == etlExecutorService || null == xmlJobService || null == js) {
			generateXmlService = (GenerateXmlService) SpringContextUtil.getBean("generateXmlService");
			etlExecutorService = (ETLExecutorService) SpringContextUtil.getBean("ETLExecutorService");
			xmlJobService = (XmlJobService) SpringContextUtil.getBean("xmlJobService");
			js = (JobLogService) SpringContextUtil.getBean("jobLogService");
		}
	}

	public static void executeJobImmediate(int xmlJobId, String jobName, String setupUser) throws EtlExecutorException, IOException, InterruptedException, ParseException {

		initServices();
		
		if(xmlJobService.isJobMultipleThread(xmlJobId)){
			executeMultiThreadJob(xmlJobId, jobName, setupUser);
		} else {
			executeNormalJob(xmlJobId, jobName, setupUser);
		}
	}
	
	private static void executeNormalJob(int xmlJobId, String jobName, String setupUser) throws EtlExecutorException, IOException, InterruptedException {
		CisJobProgressIndicator cisIndicator = new CisJobProgressIndicator();
		cisIndicator.setJobName(jobName);
		cisIndicator.setUsername(setupUser);
		cisIndicator.setJs(js);

		String xmlScript = generateXmlService.GetJobEtlXml(xmlJobId);
		System.err.println(xmlScript);
		
		etlExecutorService.execute(xmlScript, cisIndicator);
	}
	
	private static void executeMultiThreadJob(int xmlJobId, String jobName, String setupUser) throws ParseException {
		Date startDate = xmlJobService.selectStartDate(xmlJobId);
		Date endDate = xmlJobService.selectEndDate(xmlJobId);
		Integer ThreadNum = xmlJobService.selectThreadNumber(xmlJobId);
		Integer taskLoad = xmlJobService.selectTaskLoad(xmlJobId);
		
		ExecutorService service = Executors.newFixedThreadPool(ThreadNum);
		Future<Object> oFuture = service.submit(new Callable<Object>() {

			@Override
			public Object call() throws Exception {
				return null;
			}
		});
	}

}